package servlet;

import java.io.IOException;
import java.util.Iterator;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Addition;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import persistence.OfferDao;

/**
 * Servlet implementation class GetQA
 */
@WebServlet("/GetQA")
public class GetQA extends MyHttpServlet {
	private static final long serialVersionUID = 1L;
       
    
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	private void process(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			Document xmlDoc = getDocument(request);
			NodeList posContent = xmlDoc.getElementsByTagName("content")
					.item(0).getChildNodes();
			long id = Long.parseLong(posContent.item(0).getFirstChild()
					.getNodeValue());

			printWriter = response.getWriter();
			response.setContentType("application/xml");
			printWriter.write("<content>");
			printWriter.write("<entries>");
			@SuppressWarnings("unchecked")
			Set<Addition> additionSet = OfferDao.load(id).getAddition();

			Iterator<Addition> it = additionSet.iterator();
			while (it.hasNext()) {
				printWriter.write("<entry>");
				Addition buffer = it.next();
				// addTag("id", String.valueOf(buffer.getId()));
				addTag("time", buffer.getDate().toString());
				addTag("text", buffer.getDescription());
				addTag("name", buffer.getCustomer().getName());
				addTag("image", buffer.getCustomer().getStatus());
				printWriter.write("</entry>");
			}
			printWriter.write("</entries>");
			printWriter.write("</content>");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
